package com.ai.web.weixin.message.request;

import java.lang.reflect.Field;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ai.web.weixin.message.util.MessageUtil;

public class ReqMsgConvertor {
	
	private static Logger logger = Logger.getLogger(ReqMsgConvertor.class);

	public static ReqBaseMessage conver(Map<String, String> msgMap) {
		// 消息类型  
        String msgType = msgMap.get("MsgType");
        
        ReqBaseMessage bm = null;
        // 文本消息  
        if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
        	logger.info("您发送的是文本消息！");
        	bm = new TextMessage();
            converReqMsg(msgMap, bm);
        }  
        // 图片消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) { 
        	logger.info("您发送的是图片消息！");
        	bm = new ImageMessage();
            converReqMsg(msgMap, bm);
              
        }  
        // 地理位置消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {  
        	logger.info("您发送的是地理位置消息！");  
        	bm = new LocationMessage();
            converReqMsg(msgMap, bm);
              
        }  
        // 链接消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
        	logger.info("您发送的是链接消息！");  
        	bm = new LinkMessage();
            converReqMsg(msgMap, bm);
              
        }  
        // 音频消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
        	logger.info("您发送的是音频消息！"); 
        	bm = new VoiceMessage();
            converReqMsg(msgMap, bm);
               
        }  
        // 事件推送  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {  
            // 事件类型  
            String eventType = msgMap.get("Event");  
            // 订阅  
            if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {  
            	logger.info("收到关注！");  
            }  
            // 取消订阅  
            else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
            	logger.info("取消关注！");
            }  
            // 自定义菜单点击事件  
            else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
            	String eventKey = msgMap.get("EventKey");
            	logger.info("收到click event key=" + eventKey);
            	
            	bm = new ClickMessage();
            	converReqMsg(msgMap, bm);
            }  
        }  
        
        return bm;
	}
	
	private static void converReqMsg(Map<String, String> msgMap, ReqBaseMessage obj) {
		try {
			Class<ReqBaseMessage> bmClazz = (Class<ReqBaseMessage>) obj.getClass();
			for (String fieldName : msgMap.keySet()) {
				Field field = bmClazz.getDeclaredField(fieldName);
				field.setAccessible(true);
				field.set(obj, msgMap.get(fieldName));
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}
